import os
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import re


#  将监听到mq消息-websocket消息时间差的日志文件读出来以excel折线图展示


# 日志文件路径
log_file_path = 'qunayu_0903_1000ms.txt'

# 提取时长的正则表达式
duration_pattern = re.compile(r'时长:(\d+)')

# 提取时间戳的正则表达式
timestamp_pattern = re.compile(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})')

# 存储提取的数据
timestamps = []
durations = []

# 读取日志文件并提取数据
with open(log_file_path, 'r', encoding='utf-8') as file:
    for line in file:
        duration_match = duration_pattern.search(line)
        timestamp_match = timestamp_pattern.match(line)

        if duration_match and timestamp_match:
            durations.append(int(duration_match.group(1)))
            # 格式化时间戳
            timestamp = datetime.strptime(timestamp_match.group(1), '%Y-%m-%d %H:%M:%S')
            timestamps.append(timestamp)

# 生成输出文件名
base_name = os.path.splitext(log_file_path)[0]
output_file_name = f'{base_name}.png'

# 绘制折线图
plt.figure(figsize=(10, 6))
plt.plot(timestamps, durations, marker='o', linestyle='-', color='b')

# 设置标题和标签
plt.title('WebSocket Push Processing Duration Over Time')
plt.xlabel('Time')
plt.ylabel('Duration (ms)')

# 设置横坐标格式
plt.gca().xaxis.set_major_locator(mdates.SecondLocator(interval=5))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
plt.xticks(rotation=45)  # 旋转x轴标签以防重叠

# 调整布局和显示图表
plt.tight_layout()
plt.grid(True)
plt.savefig(output_file_name)  # 保存为 PNG 格式
# plt.show()